from SCons.Errors import StopError

try:
    name = ARGUMENTS['name']
except KeyError:
    raise StopError("'name=' must be provided on command line.")

extra_linkflags = ARGUMENTS.get('LINKFLAGS').split(' ')

env = Environment(
    NAME = name,
)
env.Replace(
    BUILD_DIR = env.Dir('#build.$NAME'),
    DIST_DIR = env.Dir('#dist.$NAME'),
    LIB_DIR = '$DIST_DIR/lib',
    BIN_DIR = '$DIST_DIR/bin',

    # https://github.com/SCons/scons/wiki/UsingOrigin
    LINKFLAGS = [
        '-z', 'origin',
        '-Wl,-rpath-link', '$LIB_DIR',
    ] + extra_linkflags,

    # Programs look for shared libs in ../lib
    PROG_RPATH = Literal('\\$$ORIGIN/../lib'),

    # Libraries look for shared libs in .
    LIB_RPATH = Literal('\\$$ORIGIN'),

    CCFLAGS = ['-Wall', '-Werror'],
    LIBPATH = ['$LIB_DIR'],
)

# gcc (ld) requires that -rpath-link dirs be present, but they may not (yet) exist
env.Execute(Mkdir('$LIB_DIR'))

env.SConscript(
    'SConscript',
    variant_dir = '$BUILD_DIR',
    duplicate = False,
    exports = dict(env = env),
)
